import {Card} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType} from '@ant-design/pro-table';
import type {TableListItem} from './data.d';
import {queryStatisticsList} from './service';
import {
  columnsSorter,
  columnToColumnsState,
  empty,
  formatDate,
  NumberDiv,
  NumberMul,
  reRedAndGreen
} from "@/utils/function";
import {queryUse} from "@/utils/service";
import {getSelectList} from "@/pages/BTCList/getSelectList";

const StatisticsList: React.FC = () => {
  //处理同步数据
  let columns: any[] = [
    {
      title: "交易对",
      dataIndex: 'symbol',
      key: 'symbol',
      fixed: "left",
      width: 90,
      tip: '交易对是唯一的 key',
    },
    {
      title: "开始时间",
      dataIndex: 'startTime',
      key: 'startTime',
      width: 120,
      renderText: (val: string) => formatDate(val, false)
    },
    {
      title: "结束时间",
      dataIndex: 'endTime',
      key: 'endTime',
      width: 120,
      renderText: (val: string) => formatDate(val, false)
    },
    {
      title: "强平价格",
      width: 120,
      dataIndex: 'liquidationPrice',
      key: 'liquidationPrice',
      renderText: (val: string | number) => NumberDiv(val,1,4)
    },
    {
      title: "合约杠杆",
      width: 120,
      dataIndex: 'leverage',
      key: 'leverage',
    },
    {
      title: "当前现货价格",
      width: 100,
      dataIndex: 'lastStockPrice',
      key: 'lastStockPrice',
    },
    {
      title: "当前合约价格",
      width: 120,
      dataIndex: 'lastContractPrice',
      key: 'lastContractPrice',
    },
    {
      title: "总盈亏",
      width: 100,
      dataIndex: 'allProfit',
      key: 'allProfit',
      renderText: (val: string | number) => reRedAndGreen(NumberDiv(val,1,4))
    },
    {
      title: "下一次资金费率",
      width: 120,
      dataIndex: 'lastFundingRate',
      key: 'lastFundingRate',
      renderText: (val: string | number) => (NumberMul(val,100,4)?(NumberMul(val,100,4)+"%"):null)
    },
    {
      title: "现货浮动盈亏",
      width: 100,
      dataIndex: 'stockProfit',
      key: 'stockProfit',
      renderText: (val: string | number) => NumberDiv(val,1,4)
    },
    {
      title: "合约浮动盈亏",
      width: 100,
      dataIndex: 'contractProfit',
      key: 'contractProfit',
      renderText: (val: string | number) => NumberDiv(val,1,4)
    },
    {
      title: "佣金/手续费",
      width: 100,
      dataIndex: 'commission',
      key: 'commission',
      renderText: (val: string | number) => NumberDiv(val,1,4)
    },
    {
      title: "套利年后收益率",
      width: 100,
      dataIndex: 'xirr',
      key: 'xirr',
      renderText: (val: string | number) => (NumberMul(val,100,4)?(NumberMul(val,100,4)+"%"):null)
    },
    {
      title: "套利收益率",
      width: 100,
      dataIndex: 'arbitrageProfitRate',
      key: 'arbitrageProfitRate',
      renderText: (val: string | number) => (NumberMul(val,100,4)?(NumberMul(val,100,4)+"%"):null)
    },
    {
      title: "套利利润",
      width: 100,
      dataIndex: 'arbitrageProfit',
      key: 'arbitrageProfit',
      renderText: (val: string | number) => NumberDiv(val,1,4)
    },
    // {
    //   title: "现货买入成本价格",
    //   width: 120,
    //   dataIndex: 'goodsPrice',
    //   key: 'goodsPrice',
    // },
    // {
    //   title: "现货数量",
    //   width: 100,
    //   dataIndex: ' stockCount',
    //   key: ' stockCount',
    // },
    // {
    //   title: "期货买入成本价格",
    //   width: 100,
    //   dataIndex: 'contractPrice',
    //   key: 'contractPrice',
    // },
    // {
    //   title: "期货数量",
    //   width: 100,
    //   dataIndex: 'contractNum',
    //   key: 'contractNum',
    // },
  ];
  columnsSorter("StatisticsList永续合约期现套利统计", columns);
  const [col, setCol] = useState<any>(columnToColumnsState(columns));
  const [dataTable, setDataTable] = useState<any>(null);
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    getSelectList("1","StatisticsList", actionRef).then(
      (selectList: React.ReactNode)=>{
        setDataTable(<ProTable<TableListItem>
          headerTitle={""}
          rowKey="key"
          bordered
          actionRef={actionRef}
          columnsStateMap={col}
          onColumnsStateChange={(e) => {
            if (!empty(e)) {
              localStorage.setItem("StatisticsList永续合约期现套利统计", JSON.stringify(e));
              setCol(e);
            }
          }}
          toolBarRender={() => [
            <div>{selectList}</div>,
          ]}
          pagination={false}
          scroll={{x: 2000, y: 666}}
          search={false}
          request={async (params = {}, sort, filter) => {
            //console.log(sort, filter);
            const msg = await queryStatisticsList();
            let data = queryUse(msg)
            //sum
            let sumItem: any = {
              symbol: "合计",
              arbitrageProfit: 0,
              commission: 0,
              contractProfit:0,
              stockProfit:0,
              allProfit:0,
            }
            for (let i = 0; i < data.length; i++) {
              const item = data[i];
              sumItem.arbitrageProfit += (item.arbitrageProfit ? item.arbitrageProfit : 0);
              sumItem.commission += (item.commission ? item.commission : 0);
              sumItem.contractProfit += (item.contractProfit ? item.contractProfit : 0);
              sumItem.stockProfit += (item.stockProfit ? item.stockProfit : 0);
              sumItem.allProfit += (item.allProfit ? item.allProfit : 0);
              // ids.push(item.id)
            }
            data.unshift(sumItem)
            if (data) {

           /*   //sum
              let sumItem: any = {
                symbol: "合计",
                allProfit: 0,
              }
              for (let i = 0; i < data.length; i++) {
                const item = data[i];
                sumItem.allProfit += (item.allProfit ? item.allProfit : 0);
              }
              data.unshift(sumItem)*/

              return {
                data: data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                // total: number,
              };

            } else {
              return {
                data: data,
                success: false,
              };
            }
          }}
          columns={columns}
        />)
      });
  }, [col]);

// debugger
  return (
    <PageContainer>
      <Card>
        {dataTable}
      </Card>
    </PageContainer>
  );
};

export default StatisticsList;
